<template>
  <div class="Simulation-Classlist-panel">
    <div>
      <img src="@/assets/img/other/icon-班级列表.png" class="Simulation-img-Classlist" /><span
        class="Simulation-Classlist-span">班级列表</span>
      <div class="Simulation-createclass-button" v-show="State.Role === '1' && State.RouterName === 'ClassManagement'"
        @click="CreateClassDialogFn"><span class="Simulation-createclass-span">创建班级</span>
      </div>
      <div class="Simulation-createclass-button" v-show="State.Role === '2'" @click="AddClassDialogFn">
        <span class="Simulation-createclass-span">加入班级</span>
      </div>
    </div>

    <div class="Simulation-Classlist-panel-moder" v-loading="State.Loading">
      <el-scrollbar class="infinite-list">
        <div class="Simulation-Classlist-panel-span-moder" v-for="(its, classindex) in State.AllClass" :key="classindex"
          :class="selectedIndex == classindex ? 'active' : ''" @click="GetClassInformation(classindex)">
          <span class="Simulation-Classlist-span-name">{{ its.name }}</span>
        </div>
      </el-scrollbar>
    </div>
    <!-- 加入班级 -->
    <div class="AddClass-Panel">
      <el-dialog title="提示" v-model="State.AddClassDialogboolean" top="30vh" :close-on-click-modal="false"
        @close="AddClassDialogcloses">
        <div class="AddClass-Panel-body">
          <div class="AddClass-Panel-body-code">
            <div>
              <span>邀请码 :</span>
            </div>
            <div>
              <el-input v-model="State.ClassCode"></el-input>
            </div>
            <div @click="VerificationClassCode">
              <span>验证邀请码</span>
            </div>
          </div>
          <div class="AddClass-Panel-body-codename">
            <div>
              <span>班级名称 :</span>
            </div>
            <div>
              <el-input v-model="State.ClassName"></el-input>
            </div>
          </div>
        </div>
        <div class="AddClass-Panel-btn">
          <div @click="AddClassSumbit">
            <span>确定</span>
          </div>
          <div @click="State.AddClassDialogboolean = false">
            <span>取消</span>
          </div>
        </div>
      </el-dialog>
    </div>
    <!-- 创建班级对话框 -->
    <DialogComponentInput :DialogComponent="CreateClassDialog" @click="CreateTeacherClass" ref="getref">
    </DialogComponentInput>
    <!-- 创建班级提示对话框 -->
    <DialogComponents :DialogComponent="ComponDialogComponent" @click="ComponDialogComponentFn"></DialogComponents>
  </div>
</template>

<script>
import { postData } from "@/assets/js/pubilcs.js";
import router from '@/router'
import bus from "@/bus.js";
import { defineComponent, reactive, ref, watch, toRef, toRefs, inject, onMounted } from "vue";
import DialogComponentInput from "@/components/compon/DialogComponentInput.vue";
import DialogComponents from "@/components/compon/DialogComponents.vue";
import { ElMessage, ElMessageBox } from 'element-plus'
export default defineComponent({
  name: "TeacherTasksClassList",
  components: {
    DialogComponentInput,
    DialogComponents
  },
  props: {
  },
  setup(props, context) {
    let State = reactive({
      AllClass: [],
      RouterName: '',
      ProductId: sessionStorage.getItem('productId'),
      ClassProbablyInformation: "",
      Role: sessionStorage.getItem('role'),
      //加入班级对话框显示
      AddClassDialogboolean: false,
      //班级码
      ClassCode: '',
      // 学校Id
      SchoolId: '',
      // 产品Id
      ProductId: '',
      //班级名称
      ClassName: '',
      Loading: "true",
    })
    let getref = ref(null)
    let selectedIndex = ref(0)
    //加入班级对话框隐藏
    function AddClassDialogcloses() {
      State.AddClassDialogboolean = false
    }
    //验证班级码
    function VerificationClassCode() {
      if (!State.ClassCode) {
        ElMessageBox.alert('邀请码不能为空', '提示', {
          confirmButtonText: '确定',
        })
        return
      }
      postData("/api/CourseManage/GetByInviteCode", JSON.stringify({ InviteCode: State.ClassCode }), sessionStorage.getItem("token")).
        then(function (Code) {
          if (Code.result.success === false) {
            ElMessageBox.alert(Code.result.msg, '提示', {
              confirmButtonText: '确定',
            })
          } else {
            State.ClassName = Code.result.result.name
            ElMessageBox.alert(Code.result.result.name, '提示', {
              confirmButtonText: '确定',
            })
          }
        })
        .catch((error) => {

        });
    }
    //确定加入对话框
    function AddClassSumbit() {
      // VerificationClassCode()
      postData("/api/CourseManage/Join", JSON.stringify({ userId: sessionStorage.getItem("userid"), inviteCode: State.ClassCode, SchoolId:sessionStorage.getItem("schoolId"),ProductId:sessionStorage.getItem("productId") }), sessionStorage.getItem("token")).
        then(function (Code) {
          console.log('确定加入----',Code);
          if (Code.result.success) {
            console.log('Code.result.success', Code.result.success);
            GetTeacherAllClass()
            State.AddClassDialogboolean = false
            ElMessage({
              message: '加入成功',
              type: 'success',
            })
          } else if (!State.ClassCode && !State.ClassName) {
            ElMessageBox.alert('邀请码和班级不能为空', '提示', {
              confirmButtonText: '确定',
            })
          }else if (!State.ClassCode && State.ClassName) {
            ElMessageBox.alert("邀请码不能为空", '提示', {
              confirmButtonText: '确定',
            })
          } else if (Code.result.success === false) {
            ElMessageBox.alert(Code.result.msg, '提示', {
              confirmButtonText: '确定',
              customClass: 'myClass',
              // ----------------------------------------------------
            })
          } else {
            ElMessageBox.alert("已加入,请勿重复加入", '提示', {
              confirmButtonText: '确定',
            })
          }
        })
        .catch((error) => { });
    }
    //没有激活产品时的提示(通用对话框)
    let ComponDialogComponent = reactive({
      Dialogboolean: false,
      Msg: "请先激活该产品!",
      Speanstyles: {

      },
      Buttonstyle: {
        background: 'linear-gradient(-90deg, #0974D8, #3D8EF1, #7C7FF8)'
      },
      Buttonname: "确定",
    })
    //创建班级对话框
    function CreateClassDialogFn() {
      if (sessionStorage.getItem('productId') === '99999') {
        //没有产品的情况下提示激活产品
        ComponDialogComponent.Dialogboolean = true
      } else {
        //加入班级对话框显示
        CreateClassDialog.Dialogboolean = true
      }
    }
    //加入班级对话框操作
    function AddClassDialogFn() {
      // console.log('班级列表wefasdfgasdgsdfg', State.AllClass);
      if (sessionStorage.getItem('productId') === '99999') {
        ComponDialogComponent.Dialogboolean = true
      } else {
        //显示对话框
        State.AddClassDialogboolean = true
        //清空2个输入框
        State.ClassName = ''
        State.ClassCode = ''
      }
    }
    //通用对话框
    function ComponDialogComponentFn(fn) {
      if (fn === 'Cancel') {
        ComponDialogComponent.Dialogboolean = false
      }
      if (fn === 'Ready') {
        ComponDialogComponent.Dialogboolean = false
      }
    }
    //创建班级信息
    let CreateClassDialog = reactive({
      Dialogboolean: false,
      Msg: "班级名称 : ",
      Speanstyles: {

      },
      Buttonstyle: {
        background: 'linear-gradient(-90deg, #0974d8, #3d8ef1, #7c7ff8)'
      },
      Buttonname: "确定",
      Tips: {
        TipsError: '',
        TipsErrorBoolean: false,
      }
    })
    //更新实训任务
    bus.$off("UpdateSimulationTasks")
    //更新实训任务
    bus.$on('UpdateSimulationTasks', (data) => {
      GetClassInformation(parseInt(data))
    })
    //创建班级
    function CreateTeacherClass(fn) {
      if (fn === 'Ready') {
        postData("/api/CourseManage/Create", JSON.stringify({ name: getref.value.key, creatorId: sessionStorage.getItem("userid"), productId: sessionStorage.getItem("productId"), schoolId: sessionStorage.getItem("schoolId") }), sessionStorage.getItem("token"))
          .then(function (rep) {
            console.log('确定创建班级获取的信息', rep);
            if (rep.result.success) {
              postData("/api/CourseManage/GetCourseByCreatorId", JSON.stringify({ creatorId: sessionStorage.getItem("userid"), ProductId: sessionStorage.getItem("productId") }), sessionStorage.getItem("token"))
                .then(function (reps) {
                  //获取所有的班级
                  State.AllClass = reps.result.result.courseGroup
                  CreateClassDialog.Dialogboolean = false
                  bus.$emit("UpdateHomeTaskPanel", "Updates")

                })
                .catch((error) => {

                });
            } else {
              getref.value.Tips.TipsErrorBoolean = true
              getref.value.Tips.TipsError = "班级名重复"
            }
          })
          .catch((error) => {

          });
      }
      if (fn === 'Cancel') {
        CreateClassDialog.Dialogboolean = false
      }

    }
    //监听父组件传过来的数据
    watch(() => State.AllClass, (val, old) => {
      if (old !== val) {
        if (router.currentRoute.value.name === 'SimulationTasks') {
          //判断为0用来处理没有数据
          if (val.length === 0) {
            return
          } else {
            //获取班级的信息传递给父组件SimulationTasks
            GetClassInformation(0)
          }
        }
        //获取当前的路由
        State.RouterName = router.currentRoute.value.name
      }
    },
      {
        deep: true
      }
    )
    //获取所有老师的班级
    function GetTeacherAllClass() {
      //每次选择产品时,默认选中第一个
      selectedIndex.value = 0
      //用户ID
      let userid = sessionStorage.getItem("userid")
      //产品ID
      let ProductId = sessionStorage.getItem("productId")
      //教师角色
      if (sessionStorage.getItem("role") === '1') {
        postData("/api/CourseManage/GetCourseByCreatorId", JSON.stringify({ creatorId: userid, ProductId: ProductId }),
          sessionStorage.getItem("token")
        )
          .then(function (response) {
            if (response.result.result.courseGroup) {
              State.Loading = false
              //获取所有的班级
              State.AllClass = response.result.result.courseGroup
              //传递所有的班级到实训任务板块,用于判断是否没有创建班级
              bus.$emit("AllClass", response.result.result.courseGroup)
            } else {
              State.Loading = false
              //设置班级数据为空
              State.AllClass = []
              //传递具体的班级信息为空
              context.emit("GetStudentallInformation", [])
              bus.$emit("AllClass", State.AllClass)
            }
          })
          .catch((error) => {
            console.log(error)
          });
      }
      //学生角色
      if (sessionStorage.getItem("role") === '2') {
        postData("/api/CourseManage/GetCourseByUserId", JSON.stringify({ userId: userid, ProductId: ProductId }),
          sessionStorage.getItem("token")
        )
          .then(function (response) {
            if (response.result.result.courseGroup) {
              State.Loading = false
              //获取所有的班级
              State.AllClass = response.result.result.courseGroup
            } else {
              State.Loading = false
              //设置班级数据为空
              State.AllClass = []
              //传递具体的班级信息为空
              context.emit("GetStudentallInformation", [])
            }
          })
          .catch((error) => {
            console.log(error)
          });
      }
    }
    //获取当前选择的班级
    function GetClassInformation(classindex) {
      //储存选中班级的index,用于创建实训任务时执行的操作
      bus.$emit('classindex', classindex)
      //存储选中班级的名称
      bus.$emit('classname', State.AllClass[classindex].name)
      //选中班级的样式
      selectedIndex.value = classindex
      //班级ID
      let id = State.AllClass[classindex].id
      // sessionStorage.setItem('CLASSID',id)
      console.log('id',id);
      //存储选中班级的班级id
      bus.$emit('classid', id)
      if (router.currentRoute.value.name === 'SimulationTasks') {
        //教师获取实训任务
        if (sessionStorage.getItem("role") === '1') {
          postData("/api/TrainingTask/GetByCourseId", JSON.stringify({ id: id }), sessionStorage.getItem("token")).
            then(function (rep) {
              console.log('教师获取实训任务',rep);
              if (rep.success) {
                //获取班级的信息传递给父组件SimulationTasks,学生的具体信息
                context.emit("GetStudentallInformation", rep.result.result)
              }
            })
            .catch((error) => {

            });
          //学生获取实训任务
        } else if (sessionStorage.getItem("role") === '2') {
          postData("/api/TaskManage/GetByUserIdAndCourseId", JSON.stringify({ userId: sessionStorage.getItem("userid"), ProductId: sessionStorage.getItem("productId"), CourseId: id }), sessionStorage.getItem("token")).
            then(function (rep) {
              // console.log('学生获取实训任务',rep);
              if (rep.success) {
                context.emit("GetStudentallInformation", rep.result.result.taskGroup)
              }
            })
            .catch((error) => {

            });
        }
      } else if (router.currentRoute.value.name === 'ClassManagement') {
        //选择的值传递给父组件
        context.emit("GetTeacherOrStudentIndex", classindex)
        //班级管理时查询班级具体信息
        GetClassSpecificInformation(classindex)
      }
    }
    //获取班级里面学生具体信息
    function GetClassSpecificInformation(index) {
      let ProductId = sessionStorage.getItem("productId")
      let classid = State.AllClass[index].id;
      postData("/api/User/GetUsersByCourseId", JSON.stringify({ courseId: classid, productId: ProductId }), sessionStorage.getItem("token")).
        then(function (rep) {
          console.log('获取班级中的学生信息',rep);
          //学生的具体信息
          if (rep.success && rep.result.result.userGroup) {
            context.emit("GetClassSpecificInformations", rep.result.result.userGroup)
          } else {
            context.emit("GetClassSpecificInformations", [])
          }

        })
        .catch((error) => {

        });
    }
    onMounted(() => {
      
    });
    return {
      State,
      props,
      selectedIndex,
      GetClassInformation,
      GetTeacherAllClass,
      GetClassSpecificInformation,
      CreateClassDialog,
      CreateClassDialogFn,
      getref,
      CreateTeacherClass,
      ComponDialogComponent,
      ComponDialogComponentFn,
      AddClassDialogFn,
      AddClassDialogcloses,
      VerificationClassCode,
      AddClassSumbit,
      // AllClass,
    };
  },
});
</script>
<style lang="less" spce>
.el-message-box__message>p{
  text-align: center !important;
}
/*班级面板大小*/
.Simulation-Classlist-panel {
  position: absolute;
  left: 520px;
  top: 100px;
  width: 1360px;
  height: 140px;
  background: #ffffff;
  border-radius: 16px;
}

/*班级图标*/
.Simulation-img-Classlist {
  position: absolute;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  left: 19px;
  top: 19px;
}

/*班级文字*/
.Simulation-Classlist-span {
  position: absolute;
  left: 0px;
  top: 18px;
  width: 180px;
  height: 24px;
  font-size: 18px;
  color: #81859c;
  font-family: Source Han Sans CN;
  font-weight: 400;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -o-user-select: none;
}

/*班级设置*/
.Simulation-Classlist-panel-moder {
  position: absolute;
  width: 1340px;
  height: 80px;
  top: 40px;
}

/*班级设置*/
.Simulation-Classlist-panel-moder .infinite-list {
  position: absolute;
  width: 100%;
  height: 100%;
}

/*将el-scrollbar__vie的子元素设置成为块级元素*/
.Simulation-Classlist-panel-moder .el-scrollbar__view {
  display: flex;
  flex-wrap: wrap;
}

/*每一个小班级的设置*/
.Simulation-Classlist-panel-span-moder {
  width: 120px;
  height: 60px;
  margin-left: 20px;
  margin-top: 18px;
  // background: rgba(129, 133, 156, 0.5);
  background: rgba(242, 243, 245, 0.5);
  border-radius: 10px;
  font-size: 18px;
  color: #A2A5B5;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.active {
  color: #ffffff;
  background: linear-gradient(-90deg, #0974d8, #3d8ef1, #7c7ff8);
}

/*每一个小班级的设置*/
.Simulation-Classlist-panel .el-scrollbar__wrap {
  overflow-x: hidden;
}

.Simulation-Classlist-panel .Simulation-createclass-button {
  position: absolute;
  left: 1200px;
  top: 18px;
  font-size: 20px;
  width: 130px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url("../../assets/img/other/icon-添加-normal.png") 100px -1px;
  background-repeat: no-repeat;
  background-size: 21%;
  -moz-background-size: 21%;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #81859c;
  cursor: pointer;
  // border: none ;
  // outline:none;
  /*图片地址*/
  // border: 0px solid #000;
}

.Simulation-Classlist-panel .Simulation-createclass-span {
  margin-left: -15px;
  margin-bottom: 5px;
}

.Simulation-Classlist-panel .Simulation-createclass-button:hover {
  color: #0974d8;
  width: 130px;
  height: 30px;
  background: url("../../assets/img/other/icon-添加-hover.png") no-repeat 100px -1px;
  background-repeat: no-repeat;
  background-size: 21%;
  -moz-background-size: 21%;
}





//加入班级
.AddClass-Panel .el-dialog {
  width: 640px !important;
  height: 380px;
  border-radius: 20px;
  // margin-top: 30vh;
}

.AddClass-Panel .el-dialog__body {
  height: 40%;
}

.AddClass-Panel .el-dialog__header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.AddClass-Panel .el-dialog__title {
  font-size: 20px;
  font-family: Source Han Sans CN;
  font-weight: 500;
  color: #81859c;
}

.AddClass-Panel .AddClass-Panel-body {
  width: 100%;
  height: 100%;
  // background: rgba(242, 243, 245, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}

.AddClass-Panel-body-code {
  width: 86%;
  height: 60px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: flex-start;
}

.AddClass-Panel-body-code>div:nth-child(1) {
  margin-right: 20px;
  width: 120px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-size: 20px;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #81859c;
}

.AddClass-Panel-body-code>div:nth-child(2) {
  width: 39%;
}

.AddClass-Panel-body-code>div:nth-child(2) .el-input__inner {
  font-size: 20px;
  color: #81859c;
  font-family: Source Han Sans CN;
  font-weight: 400;
}

.AddClass-Panel-body-code>div:nth-child(3) {
  margin-left: 20px;
  width: 120px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(90deg, #0974d8, #3d8ef1, #7c7ff8);
  border-radius: 10px;
  font-size: 20px;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #ffffff;
  cursor: pointer;

}

.AddClass-Panel-body-codename {
  width: 86%;
  height: 60px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: flex-start;
}

.AddClass-Panel-body-codename>div:nth-child(1) {
  margin-right: 20px;
  width: 120px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-size: 20px;
  color: #81859c;
  font-family: Source Han Sans CN;
  font-weight: 400;
}

.AddClass-Panel-body-codename>div:nth-child(2) .el-input__inner {
  font-size: 20px;
  color: #81859c;
  font-family: Source Han Sans CN;
  font-weight: 400;
}

.AddClass-Panel-body-codename>div:nth-child(2) {
  width: 66%;
}

.AddClass-Panel-btn {
  margin-top: 65px;
  width: 100%;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.AddClass-Panel-btn>div:nth-child(1),
.AddClass-Panel-btn>div:nth-child(2) {
  width: 200px;
  height: 60px;
  font-size: 24px;
  font-family: Source Han Sans CN;
  font-weight: 500;
  color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 10px;
}

.AddClass-Panel-btn>div:nth-child(1) {
  background: linear-gradient(-90deg, #0974d8, #3d8ef1, #7c7ff8);
}

.AddClass-Panel-btn>div:nth-child(2) {
  background: #81859c;
}
</style>
